#include "ebm_env.h"
#include "ebm_msg.h"
#include "ebm_passback.h"
#include "bconn.h"

#define dbg printf

enum {
UNPASSIVE= 1,
PASSIVE= 2,
};

extern unsigned int nstar_crc32_ts(unsigned char *buffer,unsigned int size);

unsigned short passback_send_hearttick(unsigned char *data)
{
static unsigned int last_session_id= 1;	
	PASSBACK_FIXED_HEADER *msg;
	HEART_TICK_CONTENT* business;
	msg= (PASSBACK_FIXED_HEADER*)data;

	msg->head_flag= 0xFDFE;
	msg->version= 0x0001;
	msg->session_id= swap32(last_session_id);
	last_session_id++;
	msg->type= UNPASSIVE;
	msg->data_len= swap16(0x35);
	ebm_env_get_sourceid(msg->src_socde, 12);
	msg->items=swap16(1);
	memset(msg->items_arry, 0, 12);
	msg->business_type= PASSBACK_HEARTTICK;
	msg->business_len= swap16(0x09);
	business= (HEART_TICK_CONTENT*)&msg->business_data;

	business->sta= ebm_env_get_playsta();
	business->register_1st_time= ebm_env_get_register_1st_time();
	business->phyid_len=6;
	
	ebm_env_get_phyid(business->phyid, business->phyid_len);

	unsigned int *p_crc= (unsigned int*) (data+49);

	unsigned int crc_val= nstar_crc32_ts(data, 49);
	*p_crc= swap32(crc_val);
    return 53;
}



static int passback_rec(unsigned char *data, unsigned int len) {
    printf("passback rec %d\n", len);
    return 0;
}

static void passback_send_func(struct bsockt *b) {
    unsigned char data[100];
    if(PEND_T_S()){
        unsigned short len = passback_send_hearttick(data);
        unsigned short passback_tick= ebm_env_get_back_tp();
		if(passback_tick < 10)
			passback_tick= 10;
        bconn_send(b, data, len);
        SLEPP_T_S(passback_tick);  
    }
}
static struct bsockt passback_net_handle = \
BCONN_INIT_STRUCTURE("passback", 0, 0, passback_rec, DEFAULT_TR_OUT);

void *passback_task(void *parm)
{
    struct bsockt *b = &passback_net_handle;
    ebm_adt_passback_start();
	while(1)
	{
		bconn_machine(b);
        if(bconn_isConnect(b)) {
            bconn_block_rec(b);
            passback_send_func(b);
        }
        usleep(10*1000);
	}
	return 0;
}

void passback_net_stop(void)
{
	bconn_stop(&passback_net_handle);
}

void passback_net_restart(void)
{
    bconn_restart(&passback_net_handle);
}

void ebm_adt_passback_start(void) {
    bconn_connect(&passback_net_handle, ebm_env_get_sip(), syscfg_plat_port_get());
}


const char* visit_passback_net_sta(void)
{
	const char *sta_str[]={
		"未连接",
		"正常",
	};
	unsigned char ret=0 ;
	if(passback_net_handle.fd != FD_INVALID ){
			ret=1;
	}
	return sta_str[ret];
		
}




